import React from 'react'
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction' // needed for dayClick
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';

import moment from 'moment';

import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import Button from '@iso/components/uielements/button';
import Modals from '@iso/components/Feedback/Modal';
import Input, { Textarea } from '@iso/components/uielements/input';
import {Fieldset, Form, Label} from "../../../FirestoreCRUD/Article/Article.styles";
import Select,{ SelectOption } from '@iso/components/uielements/select';
import ModalStyle from "../../../Feedback/Modal/Modal.styles";
import WithDirection from '@iso/lib/helpers/rtl';
import axios from "../../../../http";
import Qs from 'qs'
import message from '@iso/components/Feedback/Message';
import MessageContent from "../../../Feedback/Message/Message.styles";


import Popconfirms from '@iso/components/Feedback/Popconfirm';
import PopconfirmWrapper from "../../../Feedback/Popconfirm/Popconfirm.styles";
import PageHeader from '@iso/components/utility/pageHeader';
const Popconfirm = (props) => (
    <PopconfirmWrapper>
        <Popconfirms {...props} />
    </PopconfirmWrapper>
);
const isoModal = ModalStyle(Modals);
const Modal = WithDirection(isoModal);

export default class Schedule extends React.Component {


    constructor(props) {

        super(props);

        this.state={eventList:[],userList:[],userViewList:[],modalVisible:false,modalEditVisible:false,modalViewVisible:false,calendarWeekends:true};

    }
    calendarComponentRef = React.createRef()

    showAddModal=(selectionInfo)=>{
        this.setState({modalVisible:true,title:'',start:this.format(selectionInfo.start),end:this.format(selectionInfo.end),participant:[],memo:''})
    };

    format=(date)=>{
        return moment(date).format('YYYY-MM-DD HH:mm:ss');
    }

    handleCancel = () => {
        this.setState({modalVisible:false})
    };

    eventClick=(selectionInfo)=>{
        let state={id:selectionInfo.event.id,title:selectionInfo.event.title,start:this.format(selectionInfo.event.start),end:this.format(selectionInfo.event.end),memo:selectionInfo.event.extendedProps.memo};
        let simpleUserList=selectionInfo.event.extendedProps.simpleUserList;
        let participant=new Array()
        let userViewList=new Array()
        for(let i=0;i<simpleUserList.length;i++){
            let user=simpleUserList[i];
            participant.push(user.realName+'_'+user.id)
            userViewList.push(user.name+'('+user.realName+')')
        }
        state["participant"]=participant;
        state["userViewList"]=userViewList;
        if(selectionInfo.event.extendedProps.editAble==true){
            state["modalEditVisible"]=true;
        }else{
            state["modalViewVisible"]=true;
        }

        this.setState(state)
    };

    handleEditCancel = () => {
        this.setState({modalEditVisible:false})
    };

    handleViewCancel = () => {
        this.setState({modalViewVisible:false})
    };
    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };

    onParticipantSelectChange = (value) => {
        this.setState({participant:value})
    };

    componentDidMount() {
        this.loadUserData()
    }

    getUserIds=()=>{
        let userIds=new Array()
        let participant= this.state.participant;
        for(let i=0;i<participant.length;i++){
            let p=participant[i];
            let userId=p.substring(p.indexOf('_')+1,p.length);
            userIds.push(userId)
        }
        return userIds;
    }
    //save after resizing
    eventResize=(eventInfo)=>{
        this.updateStartEnd(eventInfo);
    };
    //save after dragging
    eventDrop=(eventInfo)=>{
        this.updateStartEnd(eventInfo);
    };

    add=() =>{
        let entity={title:this.state.title,start:this.state.start,end:this.state.end,memo:this.state.memo,userIds:this.getUserIds()};
        axios.post('api/oa/work/event/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalVisible:false})
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }
            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }

    update=() =>{
        let entity={id:this.state.id,title:this.state.title,start:this.state.start,end:this.state.end,memo:this.state.memo,userIds:this.getUserIds()};
        axios.post('api/oa/work/event/update', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalEditVisible:false})
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }

    updateStartEnd=(eventInfo) =>{
        if(eventInfo.event.extendedProps.editAble==false){
            //just for refresh page
            this.setState({modalEditVisible:false})
            return;
        }
        let id =eventInfo.event.id;
        let start=this.format(eventInfo.event.start)
        let end=this.format(eventInfo.event.end)
        let entity={id:id,start:start,end:end};
        axios.post('api/oa/work/event/updateStartEnd', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.showSuccessMessage(data.message)
                }else{
                    //just for refresh the page
                    this.setState({modalEditVisible:false})
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }

    deleteById=()=> {
        axios.post('api/oa/work/event/deleteById', Qs.stringify({
            id:this.state.id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalEditVisible:false})
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }

    loadUserData=()=>{
        axios.post('api/core/access/user/findAllExceptLoginUser', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  dataList=response.data.data;
                let userList=new Array()
                for(let i=0;i<dataList.length;i++){
                    let user=dataList[i];
                    userList.push(<SelectOption key={user.realName+'_'+user.id}>{user.name+'('+user.realName+')'}</SelectOption>)
                }
               this.setState({userList:userList});
            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }
    loadEvents=(eventInfo,successCallback, failureCallback)=>{
        axios.post('api/oa/work/event/findMyAll', Qs.stringify({
            start:moment(eventInfo.start).format('YYYY-MM-DD HH:mm:ss'),
            end:moment(eventInfo.end).format('YYYY-MM-DD HH:mm:ss')
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                successCallback (data.data)
            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });
    }

    showSuccessMessage (systemMessage){
        message.success(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };
    showErrorMessage (systemMessage){
        message.error(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };


    render() {
        return (
            <LayoutContentWrapper >
                <PageHeader>
                    我的日程
                </PageHeader>
                <LayoutContent>

                    <Modal
                        visible={this.state.modalVisible}
                        title="添加"
                        onCancel={this.handleCancel}
                        footer={[
                            <Button key="back" size="small" onClick={this.handleCancel}>
                                取消
                            </Button>,
                            <Button
                                key="submit"
                                type="primary"
                                size="small"
                                onClick={this.add}
                            >
                                确定
                            </Button>,
                        ]}
                    >
                        <Form>
                            <Fieldset>
                                <Label>*开始时间:{this.state.start}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*结束时间:{this.state.end}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*事件名称:</Label>
                                <Input
                                    label="名称"
                                    placeholder="请输入事件名称"
                                    value={this.state.title}
                                    onChange={e => this.onRecordChange(e, 'title')}
                                />
                            </Fieldset>
                            <Fieldset>
                                <Label>参与人:</Label>
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    defaultValue={this.state.participant}
                                    placeholder="请选择参与人"
                                    onChange={this.onParticipantSelectChange}
                                >
                                    {this.state.userList}
                                </Select>
                            </Fieldset>
                            <Fieldset>
                                <Label>备注</Label>
                                <Textarea
                                    label="备注"
                                    placeholder="备注"
                                    rows={5}
                                    value={this.state.memo}
                                    onChange={e => this.onRecordChange(e, 'memo')}
                                />
                            </Fieldset>
                        </Form>
                    </Modal>

                    <Modal
                        visible={this.state.modalEditVisible}
                        title="编辑"
                        onCancel={this.handleEditCancel}
                        footer={[
                            <Button key="back" size="small" onClick={this.handleEditCancel}>
                                取消
                            </Button>,
                            <Button
                                key="submit"
                                type="primary"
                                size="small"
                                onClick={this.update}
                            >
                                确定
                            </Button>,
                        ]}
                    >
                        <Form>
                            <Fieldset>
                                <Label>*开始时间:{this.state.start}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*结束时间:{this.state.end}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*事件名称:</Label>
                                <Input
                                    label="名称"
                                    placeholder="请输入事件名称"
                                    value={this.state.title}
                                    onChange={e => this.onRecordChange(e, 'title')}
                                />
                            </Fieldset>
                            <Fieldset>
                                <Label>参与人:</Label>
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    defaultValue={this.state.participant}
                                    placeholder="请选择参与人"
                                    onChange={this.onParticipantSelectChange}
                                >
                                    {this.state.userList}
                                </Select>
                            </Fieldset>
                            <Fieldset>
                                <Label>备注</Label>
                                <Textarea
                                    label="备注"
                                    placeholder="备注"
                                    rows={5}
                                    value={this.state.memo}
                                    onChange={e => this.onRecordChange(e, 'memo')}
                                />
                            </Fieldset>
                            <Fieldset>
                                <Popconfirm
                                    title="确定要执行删除操作吗？"
                                    okText="是"
                                    cancelText="否"
                                    onConfirm={this.deleteById}
                                >
                                    <Button
                                        key="submit"
                                        type="danger"
                                        size="small"

                                    >
                                        删除
                                    </Button>
                                </Popconfirm>

                            </Fieldset>
                        </Form>
                    </Modal>

                    <Modal
                        visible={this.state.modalViewVisible}
                        title="查看"
                        onCancel={this.handleViewCancel}
                        footer={[
                        ]}
                    >
                        <Form>
                            <Fieldset>
                                <Label>*开始时间:{this.state.start}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*结束时间:{this.state.end}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*事件名称:{this.state.title}</Label>

                            </Fieldset>
                            <Fieldset>
                                <Label>参与人:</Label>
                                {this.state.userViewList}
                            </Fieldset>
                            <Fieldset>
                                <Label>备注</Label>
                                {this.state.memo}

                            </Fieldset>

                        </Form>
                    </Modal>



                    <FullCalendar
                        defaultView="timeGridWeek"
                        header={{
                            left: 'prev,next today',
                            center: 'title',
                            right: 'timeGridWeek,dayGridMonth,listWeek'
                        }}

                        plugins={[ dayGridPlugin, timeGridPlugin, interactionPlugin ]}
                        ref={ this.calendarComponentRef }
                        weekends={ this.state.calendarWeekends }

                        events={(eventInfo,successCallback, failureCallback)=>{this.loadEvents(eventInfo,successCallback,failureCallback)}}

                        editable={true}
                        selectable={true}
                        selectMirror={true}
                        select={(selectionInfo)=>{this.showAddModal(selectionInfo)}}

                        locale='zh-cn'
                        firstDay={1}
                        buttonText={{
                            today: '今天',
                            month: '月',
                            week: '周',
                            day: '天'
                        }}
                        allDayText='全天'
                        slotLabelFormat={{
                            hour: '2-digit',
                            minute: '2-digit',
                            meridiem: false,
                            hour12: false
                        }}
                        eventRender={(info)=>{}}

                        eventClick={this.eventClick}
                        eventResize={this.eventResize}
                        eventDrop={this.eventDrop}

                    />


                </LayoutContent>
            </LayoutContentWrapper>

        )
    }



    apiDemo = () => {

     let calendarApi = this.calendarComponentRef.current.getApi()

    }



}
